//
//  SYS_ShipGoodsView.m
//  System_App
//
//  Created by 吴健 on 2017/12/5.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_ShipGoodsView.h"
#import "SYS_ShipmentsCell.h"
#import "SYS_SelectShipAddressVC.h"
#import "CustomPickerView.h"
#import "DSShipModel.h"
#import "SYS_HomeVC.h"

@interface SYS_ShipGoodsView ()<UITableViewDelegate, UITableViewDataSource>
{
    NSMutableArray *mar_params;
    BOOL isDeleveryAll;//是否发货
}
//发货方式选择器
@property (nonatomic, strong) CustomPickerView *pickerView;
@property (nonatomic, strong) UIButton *shipButton;
@end

@implementation SYS_ShipGoodsView

- (id)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        self.backgroundColor = DSCOLOR_GRAY_BACKGROUND;
        
        _mainTableView = [[SYS_TableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 200) style:UITableViewStylePlain];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.scrollEnabled=NO;
        [self sd_addSubviews:@[_mainTableView]];
        
        _shipButton = [UIButton new];
        _shipButton.layer.masksToBounds = YES;
        _shipButton.layer.cornerRadius = 5;
        _shipButton.backgroundColor = DSCOLOR_BLUE;
        [_shipButton setTitle:@"发货" forState:UIControlStateNormal];
        [_shipButton setTitleColor:WJCOLOR_WHITE forState:UIControlStateNormal];
        [_shipButton addTarget:self action:@selector(doShipOnClicked) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_shipButton];
        
        //        [self setupAutoHeightWithBottomView:_shipButton bottomMargin:0];
        [self setUI];
    }
    return self;
}

- (void)setUI{
    self.pickerView = [[CustomPickerView alloc] init];
}

- (void)setShipmentsModel:(SYS_ShipmentModel *)shipmentsModel{
    _shipmentsModel = shipmentsModel;
    [_mainTableView reloadData];
    _mainTableView.sd_layout
    .leftSpaceToView(self, 0)
    .topSpaceToView(self, 0)
    .widthIs(SCREENWIDTH)
    .heightIs(_mainTableView.contentSize.height);
    
    _shipButton.sd_layout
    .leftSpaceToView(self, 20)
    .rightSpaceToView(self, 20)
    .topSpaceToView(_mainTableView, 20)
    .heightIs(40);
    
    [self setupAutoHeightWithBottomView:_shipButton bottomMargin:0];
}

#pragma mark -- touch and event
- (void)doSelectAddressAction:(UIButton *)sender{
    NSIndexPath*indexPath = [NSIndexPath indexPathForRow:0 inSection:sender.tag-100];
    SYS_ShipmentsCell *cell1 = (SYS_ShipmentsCell *)[_mainTableView cellForRowAtIndexPath:indexPath];
    UList *listModel = _shipmentsModel.uList[sender.tag-100];
    SYS_SelectShipAddressVC *vc = [[SYS_SelectShipAddressVC alloc] initWithDataArray:listModel.addressList];
    //    __weak typeof(self) weakSelf = self;
    vc.shipAddressDidSelect = ^(NSString *address, NSString *ID) {
        NSLog(@"新的地址:%@", address);
        //        _addressLabel.text = address;
        //        _sAddressId        = ID;
        listModel.shipAddressId = ID;
        cell1.addressLabel.text = address;
        cell1.lc_addressLabelHeight.constant = [DSUtility heightOfString:cell1.addressLabel.text font:DSFONT_DETAIL width:SCREENWIDTH-26 maxHeight:999]+1;
        cell1.lc_addressViewHeight.constant = 40+cell1.lc_addressLabelHeight.constant+1;
        [cell1 updateConstraintsIfNeeded];
    };
    [[self viewController].navigationController pushViewController:vc animated:YES];
}

- (void)doSelectShipWayClicked:(UIButton *)sender{
    NSIndexPath*indexPath = [NSIndexPath indexPathForRow:0 inSection:sender.tag-200];
    SYS_ShipmentsCell *cell1 = (SYS_ShipmentsCell *)[_mainTableView cellForRowAtIndexPath:indexPath];
    UList *listModel = _shipmentsModel.uList[sender.tag - 200];
    NSMutableArray *mar_data = [NSMutableArray new];
    for (int i = 0; i < listModel.deliveryWayList.count; i++) {
        DeliveryWayList *model = listModel.deliveryWayList[i];
        [mar_data addObject:model.name];
    }
    if (mar_data.count >0) {
        self.pickerView.dataSource = mar_data;
        self.pickerView.pickerTitle = @"发货方式";
        self.pickerView.valueDidSelect = ^(NSString *value) {
            NSLog(@"选则的发货方式:%@",value);
            NSArray * stateArr = [value componentsSeparatedByString:@"/"];
            cell1.shipWayLabel.text = stateArr[0];
            listModel.deliveryWayId = stateArr[1];
        };
        [self.pickerView show];
    }
}

//发货
- (void)doShipOnClicked{
    NSLog(@"发货啦");
    mar_params = [NSMutableArray new];
    for (int i = 0; i < _shipmentsModel.uList.count; i++) {
        NSIndexPath*indexPath = [NSIndexPath indexPathForRow:0 inSection:i];
        SYS_ShipmentsCell *cell = (SYS_ShipmentsCell *)[_mainTableView cellForRowAtIndexPath:indexPath];
        UList *listModel = _shipmentsModel.uList[indexPath.section];
        listModel.logisticsName = cell.companyTextField.text;
        listModel.logisticsNumber = cell.numberTextField.text;
        listModel.logisticsContact = cell.phoneTextField.text;
        NSMutableDictionary *mdc_params = [NSMutableDictionary new];
        //商品id
        NSMutableString *sIds = [NSMutableString new];
        for (int j = 0; j < listModel.orderItems.count; j++) {
            OrderItems *orderModel = listModel.orderItems[j];
            
            if (listModel.orderItems.count>1)
            {
                if (orderModel.isSelect==NO) {
                    [DSUtility mbSay:@"至少选择一种物流模板的全部商品"];
                    return;
                }
                [sIds appendString:orderModel.orderItemId];
                [sIds appendString:@","];
            }
            else
            {
                if (orderModel.isSelect==YES)
                {
                    [sIds appendString:orderModel.orderItemId];
                    [sIds appendString:@","];
                }
            }
        }
        if (sIds.length > 0) {
            NSString *s = [sIds substringToIndex:sIds.length-1];
            listModel.ids = s;
            if (listModel.logisticsContact.length == 0) {
                [DSUtility mbSay:@"请输入联系电话"];
                return;
            }
            if (listModel.logisticsNumber.length == 0) {
                [DSUtility mbSay:@"请输入快递单号"];
                return;
            }
            if (listModel.logisticsName.length == 0) {
                [DSUtility mbSay:@"请输入物流公司"];
                return;
            }
            [mdc_params setValue:listModel.ids forKey:@"ids"];
            [mdc_params setValue:listModel.shipAddressId forKey:@"shipAddressId"];
            [mdc_params setValue:listModel.deliveryWayId forKey:@"deliveryWayId"];
            [mdc_params setValue:listModel.logisticsName forKey:@"logisticsName"];
            [mdc_params setValue:listModel.logisticsNumber forKey:@"logisticsNumber"];
            [mdc_params setValue:listModel.logisticsContact forKey:@"logisticsContact"];
            [mar_params addObject:mdc_params];
        }
    }
    if (mar_params.count == 0) {
        [DSUtility mbSay:@"请选择商品"];
        return;
    }
    isDeleveryAll = YES;
   
    UICKeyChainStore *keychainStore = [UICKeyChainStore keyChainStore];
    NSString *pid = [keychainStore stringForKey:@"pid"];
    NSString *session = session = [SYS_LoginModel instance].sessionInfo.session;
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:session forKey:@"session"];
    [params setValue:_shipmentsModel.userOrderId forKey:@"orderId"];
    [params setValue:pid forKey:@"pid"];
    [params setValue:[DSUtility arrayToJSONString:mar_params] forKey:@"json"];
    [self getDeliverRequestByDictionary:params];
}

//发货接口
- (void)getDeliverRequestByDictionary:(NSDictionary *)dic{
    [SYS_HttpUtility getShipOrderRequest:dic success:^(id sender) {
        if ([sender[@"flag"] isEqualToString:@"true"]) {
            if ([JSON(sender[@"data"][@"orderStatus"]) isEqualToString:@"waitDelivery"]) {
                isDeleveryAll=NO;
            }
            [DSUtility mbSay:@"发货成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"REFRESHSTOREORDER" object:@(isDeleveryAll) userInfo:nil];
            NSMutableArray *mar = [[NSMutableArray alloc] initWithArray:[self viewController].navigationController.viewControllers];
            for (int i = 0; i < mar.count; i++) {
                UIViewController *ctr = mar[i];
                if ([ctr isKindOfClass:[SYS_HomeVC class]] ) {
                    [[self viewController].navigationController popToViewController:ctr animated:YES];
                    return;
                }
                [[self viewController].navigationController popToRootViewControllerAnimated:YES];
            }
        }else{
            [DSUtility mbSay:sender[@"exp"]];
        }
    } failure:^(id sender) {
        RequestFailure;
    }];
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UList *listModel = _shipmentsModel.uList[indexPath.section];
    return (360-125)+125*listModel.orderItems.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 10)];
    v.backgroundColor = DSCOLOR_GRAY_BACKGROUND;
    return v;
}

#pragma mark -- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _shipmentsModel.uList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"SYS_ShipmentsCell";
    SYS_ShipmentsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [SYS_ShipmentsCell getShipmentsCell];
    }
    cell.index = indexPath;
    cell.shipmentModel = _shipmentsModel;
    cell.addressButton.tag = 100+indexPath.section;
    cell.shipWayButton.tag = 200+indexPath.section;
    [cell.phoneTextField setValue:@11 forKey:@"LimitInput"];
    [cell.numberTextField setValue:@30 forKey:@"LimitInput"];
    [cell.companyTextField setValue:@30 forKey:@"LimitInput"];
    [cell.addressButton addTarget:self action:@selector(doSelectAddressAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.shipWayButton addTarget:self action:@selector(doSelectShipWayClicked:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

#pragma mark -- Custom
- (UIViewController *)viewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

@end
